package com.bluesky.plum.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;

import com.bluesky.plum.domain.Person;
import com.bluesky.plum.richdomain.FieldType;

public class FieldUtil {
	public static String[] getFieldNames(Object obj) {
		PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(obj);
		List<String> names = new ArrayList<String>();
		for (PropertyDescriptor pd : pds) {
			if(!pd.getName().equals("class"))
				names.add(pd.getName());
		}
		
//		Field[] fields = obj.getClass().getDeclaredFields();
//		String[] names = new String[fields.length];
//		for (int i = 0; i < fields.length; i++) {
//			names[i] = fields[i].getName();
//		}
//		
		return names.toArray(new String[]{});
	}

	public static Object[] getFieldValues(Object obj, String[] fieldNames) {
		Object[] values = new Object[fieldNames.length];
		int i = 0;
		for (String name : fieldNames) {
			try {
			
				values[i] = PropertyUtils.getProperty(obj, name);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException(e);
			}

			i++;
		}

		return values;
	}

	public static String printFields(Object obj) {

		StringBuilder sb = new StringBuilder();

		Field[] fields = obj.getClass().getDeclaredFields();
		PropertyDescriptor[] pds= PropertyUtils.getPropertyDescriptors(obj);

		for(PropertyDescriptor pd : pds){
			
		}
		
		for (Field f : fields) {

			FieldType fieldType = FieldType.getType(f.getType());
			if (fieldType == FieldType.ObjectReference) {
				sb.append("[" + f.getName() + ":" + "[object]" + "] ");
			} else if (fieldType == FieldType.Collection) {
				sb.append("[" + f.getName() + ":" + "[collection]" + "] ");
			} else {
				Object fieldValue = null;
				try {
					fieldValue = PropertyUtils.getProperty(obj, f.getName());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					//throw new RuntimeException(e);
				}

				sb.append("[" + f.getName() + ":" + fieldValue + "] ");
			}

		}
		return sb.toString();
	}

	public static void main(String[] args) {
		Person p = Person.getSample();
		String name;
		try {
			name = (String) PropertyUtils.getProperty(p, "name");
			System.out.println(name);
			PropertyUtils.setProperty(p, "name", "rose");
			System.out.println(p.getName());

			System.out.println(p);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
